import { useState, useEffect } from 'react';
import { useI18n, type Locale } from '@/utils/in18';

export type SupportedLanguage = 'en' | 'fr' | 'ru' | 'es' | 'ja';

interface TermsData {
    title: string;
    lastModified: string;
    sections: {
        [key: string]: {
            title: string;
            content: string;
        };
    };
}

export const useTermsI18n = (folderName: string = 'Terms') => {
    const { locale } = useI18n(); // 使用全局i18n系统
    const [data, setData] = useState<TermsData | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    const supportedLanguages: SupportedLanguage[] = ['en', 'fr', 'ru', 'es', 'ja'];

    // 将全局locale映射到Terms支持的语言
    const mapLocaleToSupportedLanguage = (locale: Locale): SupportedLanguage => {
        if (supportedLanguages.includes(locale as SupportedLanguage)) {
            return locale as SupportedLanguage;
        }
        return 'en'; // 默认英语
    };

    // 加载语言文件
    const loadLanguageData = async (lang: SupportedLanguage) => {
        try {
            setLoading(true);
            setError(null);
            const response = await fetch(`/src/pages/${folderName}/${lang}.json`);
            if (!response.ok) {
                throw new Error(`Failed to load ${lang} language file`);
            }
            
            const languageData = await response.json();
            setData(languageData);
        } catch (err) {
            setError(err instanceof Error ? err.message : 'Failed to load language data');
            console.error('Error loading language data:', err);
        } finally {
            setLoading(false);
        }
    };

    // 监听全局语言变化
    useEffect(() => {
        const currentLanguage = mapLocaleToSupportedLanguage(locale);
        loadLanguageData(currentLanguage);
    }, [locale]); // 依赖全局locale变化

    return {
        language: mapLocaleToSupportedLanguage(locale),
        data,
        loading,
        error
    };
};